<?php

/**
 * Parse an (optionally given) HTTP Accept-Language header into an associative array.
 * By default, $_SERVER['HTTP_ACCEPT_LANGUAGE'] is used to get the header.
 *
 * @return array An associative array of quality values keyed by language codes.
 */
function http_parse_accept_header($header = null)
{
  if ( is_null($header) ) $header = $_SERVER['HTTP_ACCEPT_LANGUAGE'];

  $parsed_langs = array();
  $langs = explode(',', $header);

  foreach ($langs as $lang)
  {
    $lang_code = $quality = null;
    list($lang_code, $quality) = explode(';q=', $lang);

    if ( !isset($quality) ) $quality = 1;

    $parsed_langs[$lang_code] = $quality;
  }

  return $parsed_langs;
}

function http_unparse_accept_header($parsed_header)
{
  $parts = array();

  foreach ($parsed_header as $choise => $quality)
    $parts[] = "$choise; q=$quality"; // TODO: Check decimals

  return implode(',',  $parts);
}

function http_match_accept_header($acceptable_variants, $available_variants)
{
}

function negotiate_language($available_languages)
{
  $acceptable_langs = parse_http_accept_language();
  $best_available_quality = 0;
  $best_available_code = "";

  foreach ($acceptable_langs as $lang_code => $quality)
  {
    if ( isset($available_languages[$lang_code]) and $quality > $best_available_quality )
    {
      $best_available_quality = $quality;
      $best_available_code = $lang_code;
    }
  }

  if ( !$best_available_quality )
    $best_available_code = $fallback_lang;

  $best_available_code;

  return $best_available_code;
}

?>
